﻿using EntitySpaces.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using yncTech.BusinessObjects;
using yncTech.Common;

public partial class Admin_FinMov_FinMov001h : AdminBasePage
{
    decimal shipID = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[FinShippingMetadata.ColumnNames.ShipID] != null)
        {
            shipID = decimal.Parse(Request.QueryString[FinShippingMetadata.ColumnNames.ShipID]);
        }
        if (!IsPostBack)
        {
            FinShipping fs = new yncTech.BusinessObjects.FinShipping();
            fs.LoadByPrimaryKey(shipID);

            if (fs.ShippingStatus != ConstantValue.ShippingStatusCode.New)
            {
               // btnRemove.Visible = false;
            }
        }

    }

    protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
    {
        if (IsPostBack)
        {
            return;
        }
        GridDataBind(e.NewPageIndex);
    }

    void GridDataBind(int page)
    {

        VBoxReceiptsQuery q1 = new VBoxReceiptsQuery();
        FinShippingBoxesQuery q2 = new FinShippingBoxesQuery();

        BFThirdUnitQuery q3 = new BFThirdUnitQuery("q3");

        q1.SelectAll().Select(q2.PackageNo);
        q1.InnerJoin(q2).On(q1.BoxID == q2.BoxID);
        q1.LeftJoin(q3).On(q1.BoxLocation == q3.ThirdUnitID);
        q1.Where(q2.ShipID == shipID);
        q1.SelectAll().Select((q3.Name + q3.CartName).As("LocationName"));
        pageGrid.DataSource = q1.LoadDataTable();
        pageGrid.CurrentPage = page;
        pageGrid.DataBind();
        Session["PageData"] = pageGrid.DataSource;
    }

    protected void btnExprot_Click(object sender, EventArgs e)
    {
        var temData = Session["PageData"] as DataTable;

        if (temData != null && temData.Rows.Count > 0)
        {
            DataSet ods = new DataSet();
            DataTable expData = new DataTable();
            expData.Columns.Add(GetBoxnoOrBarcodeText());
            expData.Columns.Add("盒子编号");
            expData.Columns.Add("文档描述");
            expData.Columns.Add("存储位置");
            expData.Columns.Add("公司名称(编码)");
            expData.Columns.Add("职能部门");
            expData.Columns.Add("凭证数量");
            expData.Columns.Add("创建人");
            expData.Columns.Add("创建日期");

            for (int i = 0; i < temData.Rows.Count; i++)
            {
                DataRow dr = expData.NewRow();
                dr[0] = "'" + temData.Rows[i]["PackageNo"].ToString();
                dr[1] = "'" + temData.Rows[i]["BoxNo"].ToString();
                dr[2] = temData.Rows[i]["DocTypeName"].ToString();
                dr[3] = temData.Rows[i]["LocationName"].ToString();
                dr[4] = temData.Rows[i]["CompanyInfo"].ToString();
                dr[5] = temData.Rows[i]["DeptName"].ToString();
                dr[6] = temData.Rows[i]["ReceiptCount"].ToString();
                dr[7] = temData.Rows[i]["CreatedBy"].ToString();
                dr[8] = temData.Rows[i]["CreatedDttm"].ToString();
                expData.Rows.Add(dr);
            }
            ods.Tables.Add(expData);
            ExcelExporter ee = new ExcelExporter();
            ee.ExportToExcel(ods.Tables[0], Response, "BoxList");


        }



    }

    protected void btnRemove_Click(object sender, EventArgs e)
    {
        try
        {
            //lbMessage.Text = "";

            List<decimal> boxIDs = new List<decimal>();
            using (esTransactionScope tr = new esTransactionScope())
            {
                foreach (RepeaterItem item in pageGrid.Items)
                {
                    CheckBox chkBox = (CheckBox)item.FindControl("chk_sel");
                    if (chkBox.Checked)
                    {
                        Label lbReceipt = (Label)item.FindControl("lbBoxID");
                        boxIDs.Add(decimal.Parse(lbReceipt.Text));
                    }
                }

                if (boxIDs.Count > 0)
                {
                    FinShippingBoxesCollection shippingBoxs = new FinShippingBoxesCollection();
                    shippingBoxs.Query.Where(shippingBoxs.Query.BoxID.In(boxIDs.ToArray()) && shippingBoxs.Query.ShipID == shipID);
                    shippingBoxs.Query.Load();
                    shippingBoxs.MarkAllAsDeleted();
                    shippingBoxs.Save();

                    FinBoxCollection finBoxes = new FinBoxCollection();
                    finBoxes.Query.Where(finBoxes.Query.BoxID.In(boxIDs.ToArray()));
                    finBoxes.Query.Load();

                    foreach (var item in finBoxes)
                    {
                        item.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                        item.UpdatedDttm = DateTime.Now;
                        item.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;


                    }
                    finBoxes.Save();

                    //将盒中的凭证也设置为:待转移

                    FinBoxReceiptsCollection boxRecs = new yncTech.BusinessObjects.FinBoxReceiptsCollection();
                    boxRecs.Query.Where(boxRecs.Query.BoxID.In(boxIDs.ToArray()));
                    boxRecs.Query.Load();

                    FinReceiptCollection receipts = new yncTech.BusinessObjects.FinReceiptCollection();
                    receipts.Query.Where(receipts.Query.ReceiptID.In(boxRecs.Select(r => r.ReceiptID.Value).ToArray()));
                    receipts.Query.Load();
                    foreach (var rec in receipts)
                    {
                        rec.StorageStatus = ConstantValue.StorageStatusCode.InStock;
                        rec.UpdatedBy = LoginUserInfo.CurrentUser.LoginName;
                        rec.UpdatedDttm = DateTime.Now;
                    }
                    receipts.Save();


                }

                tr.Complete();

                GridDataBind(1);
                WebHelper.RefreshOpener();
            }

        }
        catch (Exception ex)
        {
            //lbMessage.Text = ex.Message;
        }
    }

    protected string GetBoxnoOrBarcodeText()
    {
        FinShippingQuery q1 = new yncTech.BusinessObjects.FinShippingQuery("q1");
        BFThirdUnitQuery q2 = new yncTech.BusinessObjects.BFThirdUnitQuery("q2");
        q1.LeftJoin(q2).On(q1.ToDestination == q2.ThirdUnitID);
        q1.Select(q2.ThirdType);
        q1.Where(q1.ShipID == shipID);
        DataTable data = q1.LoadDataTable();
        if (data != null && data.Rows.Count > 0 && data.Rows[0]["ThirdType"].ToString() != "JGLX003")
        {
            return "打包箱号";
        }
        else
        {
            return "外仓条形码";
        }
    }

    protected void btnRetrun_Click(object sender, EventArgs e)
    {
        string retURL = "FinMov001.aspx";
        if (!string.IsNullOrEmpty(Request.QueryString["returl"]))
        {
            retURL = Request.QueryString["returl"] + ".aspx";
        }
        Response.Redirect(retURL);
    }
}